package com.android.game;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class GameActivity extends Activity {

	private ImageView im;
	private TextView text;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		text = (TextView) this.findViewById(R.id.textView1);
		im = (ImageView) this.findViewById(R.id.imageView1);
		((Button) this.findViewById(R.id.button1))
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(
								android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
						startActivityForResult(intent, 0);
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 0) {
			if (resultCode == Activity.RESULT_OK) {
				Bitmap bm = (Bitmap) data.getExtras().get("data");
//				im.setImageBitmap(bm);

				try {
					Log.i("Result", "create root");
					File root = Environment.getExternalStorageDirectory();
					
					if(!root.exists()){
						root.mkdirs();
					}
					
					String filename = String.format("%d.jpg", System.currentTimeMillis());
					Log.i("RootPath", root.getAbsolutePath());
					FileOutputStream image = this.openFileOutput(filename, MODE_WORLD_READABLE);
					Log.i("Result", "write file");
					bm.compress(Bitmap.CompressFormat.JPEG, 100, image);
					Log.i("Result", "close stream");
					image.flush();
					image.close();
					
					Log.i("Result", "show path file");
					File file = new File(this.getFilesDir(), filename);
					text.setText(file.getPath());
					
					Bitmap bm1 = BitmapFactory.decodeFile(file.getAbsolutePath());
					im.setImageBitmap(bm1);
				} catch (FileNotFoundException e) {
					Log.i("Error", "File Not Found");
				} catch (IOException e) {
					Log.i("Error", "IO Ex");
				}
			}
		}
	}
}